package com.example1.myproject.server;

import com.example1.myproject.client.GreetingService;
import com.example1.myproject.shared.FieldVerifier;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
		GreetingService {

	public String greetServer(String input) throws IllegalArgumentException {
		// Verify that the input is valid. 
		if (!FieldVerifier.isValidName(input)) {
			// If the input is not valid, throw an IllegalArgumentException back to
			// the client.
			throw new IllegalArgumentException(
					"Name must be at least 4 characters long");
		}

		// Escape data from the client to avoid cross-site script vulnerabilities.
		input = escapeHtml(input);
					
			String[] File;  
			  String delimiter = "\n"; 
			  File = input.split (delimiter); 
			  
			  String lastword = new String();
			  String results = new String();
			  
			  //Read by lines:
			  for (int s=0; s<File.length; s++) 
			  {
				  String [] words = File [s].split(" ");
				  for (int m = 0; m < words.length;  m++)
				  {
					  
				  // Read words by words:
				  if ( m == words.length-1) {lastword = words[m];
				  break; 
				  }
				  if(!lastword.isEmpty())
				  {
					  if( words[m].equals(lastword))
					  { results = results + "repeated words" + (s + 1) + lastword + " " + words[m] + "<br/>"; 
					  lastword =  new String(); 
					  }
				  }
				  if (words[m].equals(words[m+1]))
					  results = results + "repeated words" + (s + 1) + words[m+1] + " " +  words[m] + "<br/>";
			  }}
			  return results ; 
		}
	
	
	

	private String escapeHtml(String html) {
		if (html == null) {
			return null;
		}
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
				.replaceAll(">", "&gt;");
	}
}
